<template>
	<view class="repair-container">
		<u--form labelPosition="top" :model="taskInfo" :rules="rules" labelWidth="300" ref="formRef" class="taskInfo" errorType="toast" v-if="props.isRead == 0">
			<view class="flex flex-col justify-between flex-1 h-full">
				<view class="record-content plan card">
					<view class="" style="font-weight: 700; font-size: 16px">维修信息</view>
					<u-form-item label="故障描述" required prop="remarks">
						<u--textarea
							v-model="taskInfo.remarks"
							placeholder="请输入故障描述"
							height="40px"
							:customStyle="{
								marginTop: '2px'
							}"
						></u--textarea>
					</u-form-item>
					<u-form-item label="维修开始时间" required prop="repairStartTime">
						<view @click="openTimeSelect" class="flex input-box">
							<u--input v-model="taskInfo.repairStartTime" border="none" disabled disabledColor="#ffffff" placeholder="请选择维修开始时间"></u--input>
							<image @click.stop="clearInfo(['repairStartTime', 'repairStartTimeCode'])" v-show="taskInfo.repairStartTime" src="@/static/image/delete.png" />
							<image v-show="!taskInfo.repairStartTime" src="@/static/image/calendar.png" style="width: 16px; height: 16px; margin-top: 2px" />
						</view>
					</u-form-item>
					<u-form-item label="维修结束时间" required prop="repairEndTime">
						<view @click="openTimeSelectEnd" class="flex input-box">
							<u--input v-model="taskInfo.repairEndTime" border="none" disabled disabledColor="#ffffff" placeholder="请选择维修结束时间"></u--input>
							<image @click.stop="clearInfo(['repairEndTime', 'repairEndTimeCode'])" v-show="taskInfo.repairEndTime" src="@/static/image/delete.png" />
							<image v-show="!taskInfo.repairEndTime" src="@/static/image/calendar.png" style="width: 16px; height: 16px; margin-top: 2px" />
						</view>
					</u-form-item>
					<u-form-item label="维修用时 (分钟)" required prop="repairUseTime">
						<view class="flex input-box1">
							<u--input v-model="taskInfo.repairUseTime" border="none" readonly placeholder="请选择维修开始/结束时间" class="input-self"></u--input>
						</view>
					</u-form-item>
					<u-form-item label="处理措施" required prop="faultHandleMeasure">
						<u--textarea
							v-model="taskInfo.faultHandleMeasure"
							placeholder="请输入处理措施"
							height="40px"
							:customStyle="{
								marginTop: '2px'
							}"
						></u--textarea>
					</u-form-item>
					<u-form-item required prop="repairTeamName" label="维修班组">
						<view class="flex input-box1">
							<u--input v-model="taskInfo.repairTeamName" border="none" @click="hideKeyboard" placeholder="请选择维修班组" readonly class="input-self"></u--input>
							<image @click.stop="clearInfo(['repairTeamId', 'teamCode', 'repairTeamName'])" v-show="taskInfo.repairTeamName" src="@/static/image/delete.png" />
						</view>
					</u-form-item>
					<u-form-item label="维修人员" required prop="person">
						<view class="flex input-box1">
							<u--input v-model="person" @click="showPersonPicker" border="none" placeholder="请选择维修人员" class="input-self"></u--input>
							<image @click.stop="clearInfo(['repairOrderPersons'])" v-show="taskInfo.repairOrderPersons?.length" src="@/static/image/delete.png" />
						</view>
					</u-form-item>
					<u-form-item prop="executeFiles" required label="维修图片">
						<upload-image
							:multiple="false"
							:accept="accept"
							@fileChange="getSceneExecuteFiles"
							camera="back"
							:list="taskInfo.executeFiles"
							:capture="capture"
							:key="datekeyCar"
							style="margin-top: 4px"
							folderName="eam/equ/routingInspection"
						></upload-image>
					</u-form-item>
					<view style="height: 30px" class=""></view>
				</view>
			</view>
		</u--form>
		<view v-if="props.isRead != 1" style="position: fixed; bottom: 10px; width: 100%; display: flex; justify-content: center">
			<u-button style="width: 90%; border-radius: 15px" type="primary" @click="onSave">保存</u-button>
		</view>
		<RepairInfo v-if="props.isRead == 1" :taskInfo="taskInfoData"></RepairInfo>
		<!-- 开始时间选择picker弹窗 -->
		<u-datetime-picker v-model="taskInfo.repairStartTimeCode" :show="showTime" mode="datetime" @cancel="showTime = false" @confirm="timeSelect"></u-datetime-picker>
		<!-- 结束时间选择picker弹窗 -->
		<u-datetime-picker v-model="taskInfo.repairEndTimeCode" :show="showTimeEnd" mode="datetime" @cancel="showTimeEnd = false" @confirm="timeSelectEnd"></u-datetime-picker>
		<!-- 班组选择 picker -->
		<u-picker
			:show="showCrewPicker"
			:columns="crewList"
			keyName="repairTeamText"
			immediateChange
			@cancel="showCrewPicker = false"
			@confirm="changeCrew"
			class="crew-picker"
		></u-picker>
		<!-- 维修人员 -->
		<ba-tree-picker
			ref="personPicker"
			:multiple="true"
			@select-change="personChange"
			title="维修人员"
			:selectedData="showPersonValue"
			:localdata="personList"
			valueKey="memberId"
			textKey="memberName"
			childrenKey="nodes"
			@cancel="changePersonChange"
		/>
	</view>
</template>

<script setup lang="ts">
import { ref, computed, reactive } from 'vue';
import { http } from '@/utils/http';
import { getSecondTime, getTimes, validateNumber, validateNumberCanNull } from '@/utils/common';
import { onShow, onLoad } from '@dcloudio/uni-app';
import BaTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue';
import RepairInfo from '@/pages/eam/equ/routingInspection/components/repairInfo.vue';
import UploadImage from '@/components/upload-image-ssr.vue';
import { getCrewMemberListApi, getCrewListApi } from '@/api/jt-api';
import dayjs from 'dayjs';

const props = defineProps({
	id: {
		type: String,
		default: ''
	},
	isRead: {
		type: String,
		default: '' // 1是查看
	},
	status: {
		type: String,
		default: '' // 状态
	}
});

// const mm = {
// 	id: '',
// 	createTime: '',
// 	lastUpdateTime: '',
// 	createdUserId: '',
// 	lastUpdatedUserId: '',
// 	createdUserName: '',
// 	lastUpdatedUserName: '',
// 	version: 1,
// 	assetId: '1966013727799119872',
// 	taskId: null,
// 	repairTime: '2023-09-16 00:00:00',
// 	timeOfFailure: '2023-09-16 00:00:00',
// 	repairUser: '1',
// 	repairUserName: '管理员',
// 	faultStatus: '1',
// 	repairLevel: null,
// 	repairTeamId: '1823619367483170818',
// 	repairTeamCode: 'A',
// 	repairTeamName: '维修A班',
// 	repairTeamUser: null,
// 	repairTeamSysUser: null,
// 	repairTeamUserName: null,
// 	repairTeamUserEmpNo: null,
// 	remarks: '定位销套是否磨损，脱落。（检验方法：目视）11111111111111111',
// 	answerTime: '2023-09-16 00:00:00',
// 	repairStartTime: '2023-09-16 00:00:00',
// 	repairEndTime: '2023-09-16 00:40:00',
// 	repairUseTime: 40,
// 	faultModeId: null,
// 	faultMode: null,
// 	faultPhenomenonId: null,
// 	faultPhenomenon: null,
// 	faultReasonId: null,
// 	faultReason: null,
// 	faultPositionId: null,
// 	faultPosition: null,
// 	faultHandleMeasureId: null,
// 	faultHandleMeasure: 'nulla Ut Duis',
// 	repairSituation: null,
// 	repairStatus: '4',
// 	outSourcing: '0',
// 	enabled: null,
// 	deleted: 0,
// 	assetKind: null,
// 	ids: null,
// 	assetCode: 'JEFF',
// 	assetName: 'JEFFMOJU',
// 	assetManagerId: null,
// 	assetManagerName: null,
// 	usingDepartmentId: null,
// 	usingDepartmentName: null,
// 	usingPersonName: '',
// 	images: [],
// 	repairSource: '1',
// 	repairCode: 'bx20250916006',
// 	assetTypeId: 'dcabbfe2b2df445f81f1bb14867cd173',
// 	assetTypeCode: '01',
// 	assetTypeName: '造型模具',
// 	assetBrandName: '',
// 	assetModelNo: '',
// 	locationName: null,
// 	parts: [],
// 	executeFiles: [

// 	],
// 	memo: null,
// 	repairOrderPersons: [

// 	],
// 	pointCheckDetailId: null,
// 	sparePartNumber: null,
// 	spareCode: null,
// 	spareNmae: null,
// 	spareType: null
// };

onShow(() => {
	if (props.status == '2' || props.status == '3') {
		getDeviceInfo();
	}
	getCrews();
});
const datekeyCar = ref(new Date());
const formRef = ref(null);
const taskInfo = reactive({
	// 故障描述
	remarks: '',
	// 开始时间
	repairStartTime: dayjs(new Date()).format('YYYY-MM-DD HH:mm'),
	repairStartTimeCode: null,
	// 结束时间
	repairEndTime: '',
	repairEndTimeCode: null,
	// 维修用时
	repairUseTime: null,
	// 处理措施
	faultHandleMeasure: '',
	// 维修班组
	repairTeamId: '',
	repairTeamName: '',
	teamCode: '',
	// 维修人员
	repairOrderPersons: [],
	// 维修图片
	executeFiles: []
});
// 获取工装信息（接口请求）
const taskInfoData = ref({});
async function getDeviceInfo() {
	const data: any = await http({
		method: 'GET',
		url: `/eam/eamrepairorder/getByCheckDetailId//${props.id}`,
		data: {}
	}).catch(() => {});
	if (data?.data) {
		taskInfoData.value = data?.data;
		Object.assign(taskInfo, data?.data);
		taskInfo.executeFiles = data?.data.executeFiles;
		datekeyCar.value = new Date();
		person.value = '';
		// 显示已选的名字
		taskInfo.repairOrderPersons.forEach((item, index) => {
			showPersonValue.value.push(item.personId);
			person.value = taskInfo.repairOrderPersons.length - 1 == index ? person.value + ' / ' + item.personName : person.value + ' / ' + item.personName;
		});
		getPersonList(taskInfo.repairTeamId);
	}
}
function refresh() {
	taskInfo.remarks = '';
	taskInfo.repairStartTime = '';
	taskInfo.repairStartTimeCode = '';
	taskInfo.repairEndTime = '';
	taskInfo.repairEndTimeCode = '';
	taskInfo.repairUseTime = '';
	taskInfo.faultHandleMeasure = '';
	taskInfo.repairTeamId = '';
	taskInfo.repairTeamName = '';
	taskInfo.teamCode = '';
	taskInfo.repairOrderPersons = [];
	taskInfo.executeFiles = [];
}

// 表单规则定义
// 摄像头参数设置
const capture = ref(['camera', 'album']);
const accept = ref('image');
// 获取现场图片
function getSceneExecuteFiles(list) {
	taskInfo.executeFiles = list;
}
// 校验时间
function validaterepairEndTime(rule: any, value: any, callback: any) {
	if ((taskInfo.repairStartTime && value < taskInfo.repairStartTime) || value == taskInfo.repairStartTime) {
		callback(new Error('结束时间不能小于或等于开始时间'));
	} else {
		callback();
	}
}
// 校验
function validaterepairStartTime(rule: any, value: any, callback: any) {
	if ((taskInfo.repairEndTime && value > taskInfo.repairEndTime) || value == taskInfo.repairEndTime) {
		callback(new Error('开始时间不能大于或等于结束时间'));
	} else {
		callback();
	}
}
// 表单规则定义
const rules = reactive({
	remarks: [
		{ required: true, message: '请输入故障描述', trigger: 'blur' },
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	faultHandleMeasure: [
		{ required: true, message: '请输入处理措施', trigger: 'blur' },
		{
			min: 1,
			max: 255,
			message: '长度在 1 到 255 个字符',
			trigger: 'blur'
		}
	],
	repairStartTime: [
		{ required: true, message: '请选择维修开始时间', trigger: 'blur' },
		{ validator: validaterepairStartTime, trigger: 'change' }
	],
	repairEndTime: [
		{ required: true, message: '请选择维修结束时间', trigger: 'blur' },
		{ validator: validaterepairEndTime, trigger: 'change' }
	],
	repairTeamName: [{ required: true, message: '请选择维修班组', trigger: 'change' }],
	person: [{ validator: validatePersons, trigger: 'change' }],
	executeFiles: [{ validator: validateexecuteFiles, trigger: 'change' }]
});

function validatePersons(rule: any, value: any, callback: (a?: any) => {}) {
	if (taskInfo?.repairOrderPersons?.length == 0) {
		callback(new Error('请选择维修人员'));
	} else {
		callback();
	}
}

function validateexecuteFiles(rule: any, value: any, callback: (a?: any) => {}) {
	if (taskInfo?.executeFiles?.length == 0) {
		callback(new Error('请选择维修图片'));
	} else {
		callback();
	}
}
const onSaveLoading = ref(false);
function onSave() {
	formRef.value.validate().then(async () => {
		onSaveLoading.value = true;
		await http({
			method: 'POST',
			url: props.status=='1'? `/eam/eamrepairorder/quick/repair`:`/eam/eamrepairorder/save`,
			data: { ...taskInfo, pointCheckDetailId: props.id }
		}).then((res) => {
			uni.showToast({ title: '保存成功', icon: 'success' });
			onSaveLoading.value = false;
			refresh();
			uni.navigateBack();
		});

		// 这里可补充提交逻辑
	});
}
// 开始时间
// 开始时间选择
const showTime = ref(false);
function timeSelect(e) {
	taskInfo.repairStartTime = getTimes(e.value);
	taskInfo.repairStartTimeCode = e.value;
	showTime.value = false;
	computedRepairUseTime();
}

// 计算维修用时
function computedRepairUseTime() {
	taskInfo.repairUseTime = '';
	if (taskInfo.repairEndTime && taskInfo.repairStartTime) {
		if (dayjs(taskInfo.repairEndTime).valueOf() > dayjs(taskInfo.repairStartTime).valueOf()) {
			taskInfo.repairUseTime = dayjs(taskInfo.repairEndTime).diff(dayjs(taskInfo.repairStartTime), 'minute');
		}
	}
}

function openTimeSelect() {
	if (!taskInfo.repairStartTimeCode) {
		taskInfo.repairStartTimeCode = Number(new Date());
	}
	showTime.value = true;
	uni.hideKeyboard();
}

// 结束时间选择
const showTimeEnd = ref(false);
function timeSelectEnd(e) {
	taskInfo.repairEndTimeCode = e.value;
	taskInfo.repairEndTime = getTimes(e.value);
	showTimeEnd.value = false;

	computedRepairUseTime();
}
function openTimeSelectEnd() {
	if (!taskInfo.repairEndTimeCode) {
		taskInfo.repairEndTimeCode = Number(new Date());
	}
	showTimeEnd.value = true;
	uni.hideKeyboard();
}
// 清空数据
function clearInfo(arr) {
	arr?.map((item) => {
		if (item == 'repairStartTime' || item == 'repairEndTime') {
			taskInfo.repairUseTime = null;
		}
		if (item == 'repairTeamId') {
			showPersonValue.value = [];
			taskInfo.repairOrderPersons = [];
			person.value = '';
		}
		if (item === 'repairOrderPersons') {
			taskInfo[item] = [];
			person.value = '';
			personId.value = [];
			showPersonValue.value = [];
			if (personPicker.value?._reTreeList) {
				personPicker.value._reTreeList();
			}
			return;
		}
		taskInfo[item] = '';
	});
}

// 选择其他维修人员
let showPersonValue = ref([]);
const person = ref('');
const personId = ref([]);
const personPicker = ref();
function showPersonPicker() {
	showPersonValue.value = personId.value;
	personPicker.value._initTree();
	personPicker.value._show();
}

// 获取维修人员列表
const personList = ref();
async function getPersonList(id) {
	const { data } = await http({
		method: 'POST',
		url: `/eam/eamteammember/getList`,
		data: { teamId: id }
	});
	personList.value = data;
}
function changePersonChange() {
	if (personPicker.value?._reTreeList) {
		personPicker.value._reTreeList();
	}
	showPersonValue.value = personId.value;
}
//监听选择（ids为数组）
function personChange(ids, names) {
	personId.value = ids;
	taskInfo.repairOrderPersons = [];
	ids.forEach((item) => {
		personList.value.forEach((item1) => {
			if (item == item1.memberId) {
				taskInfo.repairOrderPersons.push({
					personId: item1.memberId,
					personName: item1.memberName,
					personEmpNo: item1.memberEmpNo
				});
			}
		});
	});
	person.value = names ?? '';
	showPersonValue.value = ids;
}

/**
 * 组织键盘弹出
 */
const crewList = ref([]);
const memberList = ref([]);

// 获取班组列表
async function getCrews() {
	let list: any = (await getCrewListApi({ teamType: '1' })) || [];
	list.forEach((item) => {
		item.repairTeamText = `${item.teamCode}-${item.teamName}`;
	});
	crewList.value[0] = list;
}

const showCrewPicker = ref(false);
function hideKeyboard() {
	showCrewPicker.value = true;
	uni.hideKeyboard();
}
// 确认班组信息
const changeCrew = async (e) => {
	if (e?.value?.length) {
		taskInfo.teamCode = e.value[0].teamCode;
		taskInfo.repairTeamName = e.value[0].teamName;
		taskInfo.repairTeamId = e.value[0].id;
		getPersonList(taskInfo.repairTeamId);
	} else {
		clearRepairTeam();
		memberList.value[0] = [];
	}
	showCrewPicker.value = false;
};

// 清空联动维修班组信息
function clearRepairTeam() {
	taskInfo.repairTeamId = '';
	taskInfo.repairTeamName = '';
	taskInfo.teamCode = '';
}
</script>

<style scoped lang="scss">
uni-page-body {
	height: 100%;
	background-color: #fbfbff;
}

.card {
	background-color: #fff;
	margin: 0px 10px;
	border-radius: 8px;
	padding: 12px 12px;
	transition: all 300ms ease;
	height: 570px;
	overflow-y: auto;
	box-shadow: 0 2px 6px rgba(3, 121, 255, 0.05);
}

.btnStyle {
	width: '200px';
	color: '#fff';
	border-radius: '8rpx';
}

:deep(.u-form-item) {
	.u-form-item__body__left__content__label {
		color: #a8b2bb;
		font-size: 14px;
		margin-bottom: 1px;
	}
	.u-form-item__body__left__content__required {
		font-size: 16px;
	}
	//

	.u-textarea--disabled {
		background-color: #fff !important;
	}
	.uni-textarea-textarea {
		color: #16254e !important;
	}

	.input-box {
		width: 100%;
		border: 0.5px solid #dadbde !important;
		border-radius: 4px;
		.u-input {
			pointer-events: none;
			height: 34px;
			padding-left: 10px !important;
		}
		image {
			padding: 7px 6px;
			width: 20px;
			height: 20px;
		}
	}

	.input-box1 {
		width: 100%;
		border: 0.5px solid #dadbde !important;
		border-radius: 4px;
		.u-input {
			height: 34px;
			padding-left: 10px !important;
		}
		image {
			padding: 7px 6px;
			width: 20px;
			height: 20px;
		}
	}
}

:deep(.crew-picker) {
	.u-transition {
		z-index: 1001 !important;
	}
}
</style>
